using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net;
using System.Web;

namespace Ricciolo.PaperBoy.Environment.ExceptionHandling
{
    public partial class NotifyForm : Form
    {
        private const string ErrorReportUri = "http://ricciolo.lab.aspitalia.com/PaperBoy/Report.aspx";

        public NotifyForm()
        {
            InitializeComponent();

        }

        public NotifyForm(Exception e) : this()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(String.Format("OSVersion: {0}", System.Environment.OSVersion));
            sb.Append(e);
            message.Text = sb.ToString();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);

            if (this.backgroundWorker.IsBusy)
                this.backgroundWorker.CancelAsync();
        }

        private void sendButton_Click(object sender, EventArgs e)
        {
            this.Enabled = false;
            sendButton.Text = "Sending...";
            this.backgroundWorker.RunWorkerAsync();
        }


        public bool DisableMessage
        {
            get { return this.disableMessage.Checked; }
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            string uri = String.Format("{0}?message={1}", ErrorReportUri, HttpUtility.UrlEncode(message.Text));
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            request.Method = WebRequestMethods.Http.Post;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Accepted)
                throw new HttpException((int)response.StatusCode, response.StatusDescription);
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (MessageBox.Show(e.Error.Message, "PaperBoy", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) == DialogResult.Retry)
                {
                    this.backgroundWorker.RunWorkerAsync();
                    return;
                }
                else
                    this.disableMessage.Checked = false;
            }
            this.DialogResult = DialogResult.OK;
        }
    }
}